package fr.toto.script;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.io.IOException;
import java.io.OutputStream;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;

public class ScriptWindow extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 2638293892572677566L;
	private JTextPane sysoutPane;
	final static SimpleAttributeSet attrs = new SimpleAttributeSet();
	public OutputStream out, err;
	private int docOffset = 0;

	/**
	 * Launch the application.
	 */
	ScriptWindow(String comande) {
		
		super();

		StyleConstants.setForeground(attrs, Color.RED);
		
		this.setBounds(100, 100, 491, 611);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.getContentPane().setLayout(new GridLayout(0, 1, 0, 0));
		this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

		JScrollPane scrollPane = new JScrollPane();
		this.getContentPane().add(scrollPane, BorderLayout.NORTH);

		JLabel lblNomDuScript = new JLabel(comande);
		scrollPane.setColumnHeaderView(lblNomDuScript);

		sysoutPane = new JTextPane();
		scrollPane.setViewportView(sysoutPane);
		sysoutPane.setEditable(false);
		
		this.setVisible(true);

		out = new OutputStream() {
			@Override
			public void write(final int b) throws IOException {
				updateTextPane(String.valueOf((char) b), null);
			}

			@Override
			public void write(byte[] b, int off, int len)
					throws IOException {
				updateTextPane(new String(b, off, len), null);
			}

			@Override
			public void write(byte[] b) throws IOException {
				write(b, 0, b.length);
			}
		};

		err = new OutputStream() {
			@Override
			public void write(final int b) throws IOException {
				updateTextPane(String.valueOf((char) b), attrs);
			}

			@Override
			public void write(byte[] b, int off, int len)
					throws IOException {
				updateTextPane(new String(b, off, len), attrs);
			}

			@Override
			public void write(byte[] b) throws IOException {
				write(b, 0, b.length);
			}
		};
		
	}

	private void updateTextPane(final String text,
			final AttributeSet style) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				Document doc = sysoutPane.getDocument();
				try {
					if(text.contains("\r") && !text.contains("\n")) {
						doc.remove(docOffset,doc.getLength() - docOffset);
						doc.insertString(docOffset, text, style);
					} else  {
						doc.insertString(doc.getLength(), text, style);
						docOffset = doc.getLength();
						sysoutPane.setCaretPosition(doc.getLength() - 1);
					} 
					
				} catch (BadLocationException e) {
					throw new RuntimeException(e);
				}
			}
		});
	}
}
